package com.alibaba.serverless.service.filter;
import com.alibaba.serverless.common.filter.Filter;
import com.alibaba.serverless.common.filter.FilterInvoker;
import com.alibaba.serverless.common.constant.SmtpServiceConstants;
import com.alibaba.serverless.common.exception.BizException;
import com.alibaba.serverless.common.util.RedisUtils;
import com.alibaba.serverless.domain.ReceiveParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;

/**
 * @author mac_zyj
 */
public class EmailSendTooMuchFilter implements Filter<ReceiveParams> {
    private final Logger logger = LoggerFactory.getLogger(EmailSendTooMuchFilter.class);

    private static final String EMAIL_ERROR_MESSAGE="邮件发送次数过多，请过后再试!";

    private RedisUtils redisService=new RedisUtils();


    @Override
    public void doFilter(ReceiveParams context, FilterInvoker nextFilter) {
        String emailAddress= context.getToAddress();
        String resultString=redisService.get(emailAddress+ SmtpServiceConstants.TIMES_CHECK);
        if(null!=resultString){
            int sendTimesInLastHour =Integer.parseInt(resultString);
            if (sendTimesInLastHour>=SmtpServiceConstants.CHECK_SMTP_SEND_TIMES_TIMES_LIMITS) {
                logger.warn("Smtp Exception with error code,error message");
                throw new BizException(EMAIL_ERROR_MESSAGE);
            }
        }
        nextFilter.invoke(context);
    }
}
